import sys
sys.path.insert(0, 'third_party')
sys.path.insert(0, '.')
from config import *
from common import *
from peer import Peer
from peer_web_handler import PeerWebHandler 
defaults_map = { 'name' : '',
                    'rs_host' : RECIPE_SERVER_EXTERNAL_IP,
                    'rs_port' : RECIPE_SERVER_EXTERNAL_PORT,
                    'tracker_host' : TRACKER_EXTERNAL_IP,
                    'tracker_port' : TRACKER_EXTERNAL_PORT,  
                }

def get_first_port(port):
    from socket import socket
    sock = socket()    
    while True:
        try:
            sock.bind(('',port))
            sock.close()
            return port
        except:
            port += 1            
def main():
    args = parse_opt(defaults_map)
    if 'name' not in args or not args['name']:
        print "--name must be supplied"
        usage(defaults_map)
        sys.exit(2)                
    peer = Peer(**args)
    web_server.set_root('peer/static')
    web_server.listen(get_first_port(PEER_HTTP_PORT))
    #peer.run()
    web_server.add_static(peer.filedir, 'shared')
    web_server.register(peer, PeerWebHandler)    
    web_server.run()
if __name__=='__main__':
    main()